package me.learningandroid.ch5_3.securingbroadcast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static String BC_SECUREDSEND="me.learningandroid.ch5_3.securingbroadcast.SECUREDSEND";
    private static String PERM_SECUREDSEND="me.learningandroid.ch5_3.securingbroadcast.SECUREDSEND";
    private static String BC_SECUREDRECEIVE="me.learningandroid.ch5_3.securingbroadcast.SECUREDRECEIVE";
    private static String PERM_SECUREDRECEIVE="me.learningandroid.ch5_3.securingbroadcast.SECUREDRECEIVE";

    BroadcastReceiver broadcastReceiver1 = null;
    BroadcastReceiver broadcastReceiver2 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);

        CheckBox checkBox1 = findViewById(R.id.checkBox);
        CheckBox checkBox2 = findViewById(R.id.checkBox2);

        broadcastReceiver1 = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                checkBox1.setChecked(true);
            }
        };

        broadcastReceiver2 = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                checkBox2.setChecked(true);
            }
        };


        IntentFilter intentFilter = new IntentFilter(BC_SECUREDSEND);
        registerReceiver(broadcastReceiver1, intentFilter);

        IntentFilter intentFilter3 = new IntentFilter(BC_SECUREDRECEIVE);
        registerReceiver(broadcastReceiver2, intentFilter3, PERM_SECUREDRECEIVE,null);

        button.setOnClickListener(view -> {
            checkBox1.setChecked(false);
            sendBroadcast(new Intent(BC_SECUREDSEND), PERM_SECUREDSEND);
        });
        button2.setOnClickListener(view -> {
            checkBox2.setChecked(false);
            sendBroadcast(new Intent(BC_SECUREDRECEIVE), PERM_SECUREDRECEIVE);
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // `broadcastReceiver`在注册后，必须在对应的生命周期函数里解除注册，否则会占用系统资源。
        unregisterReceiver(broadcastReceiver1);
        unregisterReceiver(broadcastReceiver2);
    }
}